/**
 * Created With IntelliJ IDEA
 * Description:leetcode：606. 根据二叉树创建字符串
 * <a href="https://leetcode.cn/problems/construct-string-from-binary-tree/">...</a>
 * User: DELL
 * Data: 2023-01-16
 * Time: 22:36
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public String tree2str(TreeNode root) {
        StringBuffer result = new StringBuffer();
        if (root == null) {
            return result.toString();
        }
        recursion(root,result);
        return result.toString();
    }
    private void recursion(TreeNode root, StringBuffer str) {
        str.append(root.val);
        //左孩子结点不为空时
        if (root.left != null) {
            str.append('(');
            recursion(root.left,str);
            str.append(')');
            if (root.right != null) {
                str.append('(');
                recursion(root.right,str);
                str.append(')');
            }
        } else { //左孩子结点为空时
            if (root.right != null) {
                //先拼接上一对括号，避免引起歧义
                str.append('(');
                str.append(')');

                str.append('(');
                recursion(root.right,str);
                str.append(')');
            }
        }
    }
}